import React, { useEffect, useMemo, useState } from 'react'
import { NavBar, Card, Grid, Tag, Toast, Popup, Button,Space } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import axios from "./axios"
import { HeartOutline } from 'antd-mobile-icons'

export default function Collect() {
    const navigate = useNavigate()
    const back = () => navigate(-1)
    
    const [arr, setArr] = useState([])
    const [loading, setLoading] = useState(true)
    const [visible, setVisible] = useState(false)
    const [selectedItem, setSelectedItem] = useState(null)

    const getArr = async() => {
        try {
            setLoading(true)
            const userStr = localStorage.getItem('token')
            if (!userStr) {
                Toast.show('请先登录')
                navigate('/login')
                return
            }

            let userObj
            try {
                userObj = JSON.parse(userStr)
            } catch (e) {
                console.error('解析用户信息失败:', e)
                Toast.show('用户信息格式错误')
                return
            }

            if (!userObj.username || !userObj.password) {
                Toast.show('用户信息不完整')
                return
            }

            const res = await axios.get('/lzh/collect', {
                params: {
                    username: userObj.username,
                    password: userObj.password
                }
            })
            
            if (res.data?.code === 200) {
                setArr(res.data.data || [])
            } else {
                Toast.show(res.data?.msg || '获取收藏列表失败')
            }
        } catch (error) {
            console.error('获取数据失败:', error)
            Toast.show('获取收藏列表失败')
            setArr([])
        } finally {
            setLoading(false)
        }
    }

    // 取消收藏函数
    const handleUncollect = async (item) => {
        console.log('====================================');
        console.log(item);
        console.log('====================================');
        try {
            const user_id = item.user_id
            
            const res = await axios.post('/lzh/uncollect', {
                // userId: localStorage.getItem(user_id) 假设token中有用户ID
                userId: user_id, 
                itemId: item._id
            })
            
            if (res.data?.code === 200) {
                Toast.show('已取消收藏')
                setVisible(false)
                // 从当前列表中移除已取消收藏的商品
                setArr(arr.filter(i => i._id !== item._id))
            } else {
                Toast.show(res.data?.msg || '取消收藏失败')
            }
        } catch (error) {
            console.error('取消收藏失败:', error)
            Toast.show('取消收藏失败')
        }
    }

    useEffect(() => {
        getArr()
    }, [])

    const collectArr = useMemo(() => {
        return Array.isArray(arr) ? arr : []
    }, [arr])

    const handleCardClick = (item) => {
        setSelectedItem(item)
        setVisible(true)
    }

    if (loading) {
        return <div style={{ padding: 24, textAlign: 'center' }}>加载中...</div>
    }

    return (
        <div style={{ padding: '0 16px' }}>
            <NavBar onBack={back}>我的收藏</NavBar>
            
            <h2 style={{ margin: '16px 0', color: '#333' }}>收藏列表</h2>
            
            {collectArr.length === 0 ? (
                <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
                    暂无收藏商品
                </div>
            ) : (
                <Grid columns={2} gap={8}>
                    {collectArr.map(item => (
                        <Grid.Item key={item._id}>
                            <Card 
                                onClick={() => handleCardClick(item)}
                                title={item.title}
                                extra={<Tag color='primary'>{item.type}</Tag>}
                                style={{ borderRadius: '8px' }}
                            >
                                <div style={{ textAlign: 'center' }}>
                                    <img 
                                        src={item.img?.[0]?.url} 
                                        alt={item.title} 
                                        style={{ 
                                            width: '100%', 
                                            height: '120px', 
                                            objectFit: 'cover',
                                            borderRadius: '4px'
                                        }} 
                                    />
                                </div>
                                <div style={{ marginTop: '8px' }}>
                                    <div style={{ color: '#ff6b6b', fontWeight: 'bold' }}>¥{item.price}</div>
                                </div>
                            </Card>
                        </Grid.Item>
                    ))}
                </Grid>
            )}

            {/* 详情弹窗 */}
            <Popup 
                visible={visible} 
                onMaskClick={() => setVisible(false)}
                onClose={() => setVisible(false)}
                bodyStyle={{ 
                    height: '50vh',
                    padding: '16px',
                    display: 'flex',
                    flexDirection: 'column'
                }}
            >
                {selectedItem && (
                    <>
                        <div style={{ flex: 1 }}>
                            <h3 style={{ marginBottom: 8 }}>{selectedItem.title}</h3>
                            <p style={{ color: '#666', marginBottom: 4 }}>类型: {selectedItem.type}</p>
                            <p style={{ color: '#ff6b6b', fontWeight: 'bold', marginBottom: 4 }}>
                                价格: ¥{selectedItem.price}
                            </p>
                            <p style={{ color: '#666', marginBottom: 12 }}>描述: {selectedItem.desc}</p>
                            {selectedItem.img?.[0]?.url && (
                                <img 
                                    src={selectedItem.img[0].url} 
                                    alt={selectedItem.title}
                                    style={{
                                        width: '100%',
                                        maxHeight: '200px',
                                        objectFit: 'contain',
                                        marginTop: '10px'
                                    }}
                                />
                            )}
                        </div>
                        <Button 
                            block 
                            color='danger' 
                            onClick={() => handleUncollect(selectedItem)}
                            style={{ marginTop: 16 }}
                        >
                            <Space>
                                <HeartOutline />
                                取消收藏
                            </Space>
                        </Button>
                    </>
                )}
            </Popup>
        </div>
    )
}